package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category)
    {
        categoryService.save(category);
        return R.success("新增分类成功");

    }

    /**
     * 根据id修改分类信息
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category)
    {
        categoryService.updateById(category);
        return R.success("修改分类成功");
    }

    @DeleteMapping
    public R<String> delete(Long id)
    {
        categoryService.removeById(id);
        return R.success("删除分类成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(@RequestParam Integer page,
                        @RequestParam Integer pageSize)
    {
        //1、构造分页构造器pages
        Page<Category> pages = new Page<>(page, pageSize);
        //2、构造条件构造器wrapper
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //4、添加排序条件，按照修改时间优先
        wrapper.orderByDesc(Category::getSort);
        //5、执行查询
        Page<Category> categoryPage = categoryService.page(pages, wrapper);
        //6、返回状态码以及信息
        return R.success(categoryPage);
    }

    /**
     * 菜单/套餐管理-新增菜单/套餐-选择菜单/套餐分类
     * 请求服务端获取菜单分类数据并展示到下拉框中
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category)
    {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(category.getType() !=null, Category::getType,category.getType());
        //降序条件，按排序，如果排序相同按更新时间
        wrapper.orderByDesc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }





}
